package UPDchat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;
    private String msgForm;

    public TalkReceive(int port,String msgForm) {
        this.port = port;
        this.msgForm = msgForm;
        try {
            socket = new DatagramSocket(this.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] bytes = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(packet);
                byte[] data = packet.getData();
                String recevie = new String(data, 0, data.length);
                System.out.println(msgForm+": "+packet.getAddress()+"："+recevie);
                if (data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
